package cn.com.freelibra.forum.web;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.com.freelibra.forum.po.UploadFile;
import cn.com.freelibra.forum.service.UploadFileService;
import cn.com.freelibra.forum.util.MD5Util;
import cn.com.freelibra.forum.web.view.FileObject;

/**
 * 
 * @author qing
 *
 */
@Controller
@RequestMapping("/upload-file")
public class UploadFileController {
	
	@Resource
	private UploadFileService uploadFileService;

	@RequestMapping("/image")
	@ResponseBody
	public FileObject image(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request)
			throws IOException {
		FileObject fl = new FileObject();
		try{
			String path = "upload"+File.separatorChar
					+MD5Util.MD5(System.currentTimeMillis()
					+file.getOriginalFilename())
					+"."
					+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
			String urlpath = request.getContextPath() + "/" + path;
			@SuppressWarnings("deprecation")
			String realpath = request.getRealPath("")+path;
			File newFile = new File(realpath);
			file.transferTo(newFile);
			fl.setStatus(200);
			fl.setPath(urlpath);
			UploadFile tmp = new UploadFile();
			tmp.setCreateTime(new Date());
			tmp.setPathUrl(urlpath);
			tmp.setRemark(realpath);
			uploadFileService.add(tmp);
		}catch (Exception e) {
			fl.setStatus(404);
			fl.setError(e.getMessage());
		}
		return fl;
	}

	@RequestMapping("video")
	@ResponseBody
	public FileObject video(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request)
			throws IOException {
		long startTime = System.currentTimeMillis();
		System.out.println("fileName：" + file.getOriginalFilename());
		String path = request.getServletContext().getRealPath("") + file.getOriginalFilename();
		System.out.println("==========1111111======" + path);
		File newFile = new File(path);
		// 通过CommonsMultipartFile的方法直接写文件（注意这个时候）
		file.transferTo(newFile);
		String path2 = request.getServletContext().getRealPath("") + System.currentTimeMillis()
				+ file.getOriginalFilename();
		File copyfiled = new File(path2);
		System.out.println("==========3333======" + path2);
		FileUtils.copyFile(newFile, copyfiled);
		long endTime = System.currentTimeMillis();
		System.out.println("方法二的运行时间：" + String.valueOf(endTime - startTime) + "ms");
		return null;
	}
}